package cn.dev.mybatis.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DefaultDatasource extends DataSourceAdapter {
    private final List<Connection> connections = new ArrayList<>();

    private int maxPoolSize = 10;

    private int minPoolSize = 5;

    private String driver;

    private String url;

    private String username;

    private String password;

    @Override
    public Connection getConnection() throws SQLException {
        if (connections.size() < minPoolSize) {
            connections.add(DriverManager.getConnection(url, username, password));
        }
        if (connections.size() > maxPoolSize) {
            return null;
        }
        return getConnectionFromPool();
    }

    private Connection getConnectionFromPool() throws SQLException {
        for (Connection connection : connections) {
            if (!connection.isClosed()) {
                return connection;
            }
        }
        connections.clear();
        return getConnection();
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getMinPoolSize() {
        return minPoolSize;
    }

    public void setMinPoolSize(int minPoolSize) {
        this.minPoolSize = minPoolSize;
    }
}
